<!-- components/Navigation.vue -->
<script setup>
import { useRouter, useRoute } from 'vue-router'
import { computed } from 'vue'

const router = useRouter()
const route = useRoute()

// 获取所有路由对象
const routes = router.options.routes

// 获取菜单项
const menuItems = computed(() => {
  const layoutRoute = routes.find(route => route.name === 'layout1')
  return layoutRoute?.children || []
})

// 根据当前路径计算默认选中项
const activeIndex = computed(() => {
  const matchedRoutes = route.matched.filter(r => r.meta && r.meta.index)
  if (matchedRoutes.length > 0) {
    // 对于二级路由，取父菜单的 index
    return matchedRoutes[0].meta.index.split('-')[0] || 0
  }
  return 0
})

// 转换图标名称为 PascalCase
const convertToPascalCase = (str) => {
  return str.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('')
}

// 处理菜单项点击
const changeMenuItem = (index) => {
  // 检查是否是二级菜单项
  if (index.includes('-')) {
    const [parentIndex, childIndex] = index.split('-').map(Number)
    const menuItem = menuItems.value[parentIndex]?.children[childIndex]
    if (menuItem) {
      router.replace({ name: menuItem.name })
    }
  } else {
    const menuItem = menuItems.value[index]
    if (menuItem) {
      router.replace({ name: menuItem.name })
    }
  }
}

// 是否有子菜单
const hasChildren = (menuItem) => {
  return menuItem.children && menuItem.children.length > 0
}
</script>

<template>
  <el-menu
      active-text-color="rgb(64, 158, 255)"
      background-color="#555"
      class="el-menu-vertical-demo"
      :default-active="activeIndex.toString()"
      text-color="#fff"
      style="height: 100%; overflow: auto;"
      @select="changeMenuItem"
  >
    <h3 style="color: white; padding: 20px 15px; font-size: 18px;">十方智育</h3>
    <template v-for="(menuItem, index) in menuItems" :key="index">
      <el-sub-menu v-if="hasChildren(menuItem)" :index="index.toString()">
        <template #title>
          <el-icon>
            <component :is="convertToPascalCase(menuItem.meta.iconName)" />
          </el-icon>
          <span>{{ menuItem.meta.title }}</span>
        </template>
        <el-menu-item
            v-for="(childItem, childIndex) in menuItem.children"
            :key="childIndex"
            :index="`${index}-${childIndex}`"
        >
          <el-icon>
            <component :is="convertToPascalCase(childItem.meta.iconName)" />
          </el-icon>
          <span>{{ childItem.meta.title }}</span>
        </el-menu-item>
      </el-sub-menu>
      <el-menu-item v-else :index="index.toString()">
        <el-icon>
          <component :is="convertToPascalCase(menuItem.meta.iconName)" />
        </el-icon>
        <span>{{ menuItem.meta.title }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<style scoped>
</style>